const db = require('../db/index')
// 获取地址列表
exports.addresslist = (req, res) => {
    let data = req.body
    const sql = `select * from myaddress where appid=? and userId=?`
    db.query(sql, [data.appid, data.userId], (err, res2) => {
        if (err) return res.cc(err)
        res.send({
            res: res2,
        })
    })
}

// 添加地址
exports.addressadd = (req, res) => {
    const data = req.body
    if (data.default) data.default = 0
    if (data._id) {
        const sql = `update myaddress set name=?,phone=?,region=?,address=? where _id = ${data._id}`
        db.query(sql, [data.name, data.phone, data.region, data.address], (err, res2) => {
            if (err) return res.cc(err)
            res.send({
                message: '修改成功'
            })
        })
    } else {
        data.defaultStatus = 0
        const sql = 'insert into myaddress set ?'
        db.query(sql, data, (err, res2) => {
            if (err) return res.cc(err)
            res.send({
                message: '添加成功'
            })
        })
    }
}
// 删除地址
exports.addressdelete = (req, res) => {
    let id = req.query.id
    const sql = `delete from myaddress where _id in(${id})`
    db.query(sql, (err, res2) => {
        if (err) return res.cc(err)
        res.send({
            message: '删除成功'
        })
    })
}

// 修改地址为默认
exports.addressdefault = (req, res) => {
    let data = req.body
    let id = data.id
    let userId = data.userId
    const seleteSql = `select * from myaddress where userId = ?`
    db.query(seleteSql, [userId], (err, res2) => {
        let noselectId = []
        if (res2.length > 0) {
            res2.forEach((item, index) => {
                if (item._id != id) {
                    noselectId.push(item._id)
                }
            })
            const sql1 = `update myaddress set defaultStatus = 1 where _id = ${id}`
            db.query(sql1, (err, res3) => {
                if (err) return res.cc(err)
                res.send({
                    message: '修改成功'
                })
            })
            if (noselectId.length > 0) {
                const sql2 = `update myaddress set defaultStatus = 0 where _id in (?)`
                db.query(sql2, [noselectId], (err, res3) => {
                    if (err) return res.cc(err)
                })
            }
        } else {
            res.send({
                message: '修改失败'
            })
        }



    })


}
// 获取默认地址
exports.getAddressdefault = (req, res) => {
    let data = req.body
    const sql = `select * from myaddress where appid=? and userId=?`
    db.query(sql, [data.appid, data.userId], (err, res2) => {
        if (err) return res.cc(err)
        res.send({
            res: res2[0],
        })
    })
}